package com.moorror.codegenvel.utils;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.moorror.codegenvel.common.utils.JacksonUtils;
import com.moorror.codegenvel.view.window.codegen.domain.TableConstant;
import com.moorror.codegenvel.view.window.codegenxrender.domain.TableSchemaColumnDesc;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @Author jiyanghuang
 * @Date 2025/10/26 23:45
 */
public class XRenderSchemaGenUtils {

    public static String object(List<TableSchemaColumnDesc> columnList){
        ObjectNode objectNode = JacksonUtils.genObjectNode();
        objectNode.put("type", "object");
        objectNode.put("displayType", "row");
        objectNode.put("column", 1);
        objectNode.put("maxWidth", "340px");

        ObjectNode objectNodePro = JacksonUtils.genObjectNode();
        objectNode.putIfAbsent("properties", objectNodePro);
        for(TableSchemaColumnDesc columnDesc : columnList){
            if(!columnDesc.isChecked()){
                continue;
            }
            ObjectNode objColumn = JacksonUtils.genObjectNode();
            objectNodePro.putIfAbsent(columnDesc.getName(), objColumn);
            objColumn.put("title", columnDesc.getTitle());
            objColumn.put("type", TableConstant.valueTypeByWidget(columnDesc.getWidget()));
            objColumn.put("widget", columnDesc.getWidget());
            if(columnDesc.isRequired()){
                objColumn.put("required", columnDesc.isRequired());
            }
            messageNode(columnDesc.getRequiredMessage(), objColumn);

        }
        return objectNode.toPrettyString();
    }

    public static String array(List<TableSchemaColumnDesc> columnList){
        ArrayNode arrayNode = JacksonUtils.genArrayNode();
        for(TableSchemaColumnDesc columnDesc : columnList) {
            if (!columnDesc.isChecked()) {
                continue;
            }
            ObjectNode objColumn = JacksonUtils.genObjectNode();
            objColumn.put("title", columnDesc.getTitle());
            objColumn.put("dataIndex", columnDesc.getName());
            arrayNode.add(objColumn);
        }
        return arrayNode.toPrettyString();
    }

    private static void messageNode(String requiredMessage, ObjectNode parent){
        if(StringUtils.isBlank(requiredMessage)){
            return;
        }
        ObjectNode objectNode = JacksonUtils.genObjectNode();
        parent.putIfAbsent("message", objectNode);
        objectNode.put("required", requiredMessage);
    }
}
